package cn.wuxing.mediation.infoconfig.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.json.JSONUtil;
import cn.wuxing.mediation.common.core.domain.entity.IcUserWindow;
import cn.wuxing.mediation.common.core.domain.entity.IcWindow;
import cn.wuxing.mediation.common.core.domain.entity.SysDictData;
import cn.wuxing.mediation.common.exception.ServiceException;
import cn.wuxing.mediation.common.utils.DictUtils;
import cn.wuxing.mediation.common.utils.SecurityUtils;
import cn.wuxing.mediation.common.utils.bean.BeanUtils;
import cn.wuxing.mediation.infoconfig.domain.dto.AddWindowUserDTO;
import cn.wuxing.mediation.infoconfig.domain.dto.EditWindowDTO;
import cn.wuxing.mediation.infoconfig.domain.dto.RemoveWindowUserDTO;
import cn.wuxing.mediation.infoconfig.domain.vo.IcWindowDetailVO;
import cn.wuxing.mediation.infoconfig.domain.vo.IcWindowListVO;
import cn.wuxing.mediation.infoconfig.domain.vo.WindowUserVO;
import cn.wuxing.mediation.infoconfig.mapper.IcUserWindowMapper;
import cn.wuxing.mediation.infoconfig.mapper.IcWindowMapper;
import cn.wuxing.mediation.infoconfig.service.IIcMediatorCommitteeService;
import cn.wuxing.mediation.infoconfig.service.IIcWindowService;
import cn.wuxing.mediation.system.mapper.SysDictDataMapper;
import cn.wuxing.mediation.system.service.ISysDictDataService;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @description: <专窗>
 * @date: 2024/9/10 14:52
 * @author:
 * @version: 1.0
 */
@Slf4j
@Service
public class IcWindowServiceImpl implements IIcWindowService {

    @Autowired
    private IcWindowMapper icWindowMapper;

    @Autowired
    private IcUserWindowMapper icUserWindowMapper;

    @Autowired
    private SysDictDataMapper dictDataMapper;

    @Autowired
    private IIcMediatorCommitteeService mediatorCommitteeService;

    // 窗口i字典CODE
    private final String WINDOW_DICT_CODE = "bus_matter_type";


    @Override
    public List<IcWindowListVO> selectWindowList(String windowName) {
        log.info("IIcWindowService_selectWindowList_windowName_{}", windowName);

        return this.icWindowMapper.selectLikeWindowName(windowName);
    }

    @Override
    public Boolean checkWindowExistUser(Long id) {
        Integer count = this.icUserWindowMapper.selectCount(
                Wrappers.<IcUserWindow>lambdaQuery().eq(IcUserWindow::getWindowId, id));
        log.info("IIcWindowService_checkWindowExistUser_count_{}", count);
        return count > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int del(Long id) {
        log.info("IIcWindowService_del_id_{}", id);
        this.dictDataMapper.delDictDataByTypeAndValue(WINDOW_DICT_CODE, String.valueOf(id));
        List<SysDictData> dictDatas = dictDataMapper.selectDictDataByType(WINDOW_DICT_CODE);
        if (CollUtil.isNotEmpty(dictDatas)) {
            DictUtils.setDictCache(WINDOW_DICT_CODE, dictDatas);
        }
        return this.icWindowMapper.deleteById(id);
    }

    @Override
    public boolean checkNameUnique(Long id, String name) {
        if (StringUtils.isBlank(name)) {
            return false;
        }
        return this.icWindowMapper.selectCount(Wrappers.<IcWindow>lambdaQuery()
                .eq(IcWindow::getWindowName, name)
                .ne(null != id, IcWindow::getId, id)) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int update(EditWindowDTO dto) {
        log.info("IIcWindowService_update_dto_{}", JSONUtil.toJsonStr(dto));

        if (null == dto.getId()) {
            throw new ServiceException("id不能为空");
        }

        Long code = this.dictDataMapper.selectByTypeAndValue(WINDOW_DICT_CODE, String.valueOf(dto.getId()));
        if (null != code) {
            SysDictData sysDictData = new SysDictData();
            sysDictData.setDictLabel(dto.getWindowName());
            sysDictData.setDictValue(String.valueOf(dto.getId()));
            sysDictData.setDictCode(code);
            int row = this.dictDataMapper.updateDictData(sysDictData);
            if (row > 0)
            {
                List<SysDictData> dictDatas = dictDataMapper.selectDictDataByType(WINDOW_DICT_CODE);
                DictUtils.setDictCache(WINDOW_DICT_CODE, dictDatas);
            }
        }

        IcWindow icWindow = new IcWindow();
        icWindow.setId(dto.getId());
        icWindow.setWindowName(dto.getWindowName());
        icWindow.setWindowResponsibility(dto.getWindowResponsibility());
        icWindow.setMediatorCommitteeId(dto.getMediatorCommitteeId());
        icWindow.setUpdateBy(String.valueOf(SecurityUtils.getLoginUser().getUsername()));
        icWindow.setUpdateTime(DateTime.now());
        return this.icWindowMapper.updateById(icWindow);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insert(EditWindowDTO dto) {
        log.info("IIcWindowService_insert_dto_{}", JSONUtil.toJsonStr(dto));

        IcWindow icWindow = new IcWindow();
        icWindow.setWindowName(dto.getWindowName());
        icWindow.setWindowResponsibility(dto.getWindowResponsibility());
        icWindow.setCreateBy(SecurityUtils.getLoginUser().getUsername());
        icWindow.setCreateTime(DateTime.now());
        icWindow.setMediatorCommitteeId(dto.getMediatorCommitteeId());
        int insert = this.icWindowMapper.insert(icWindow);

        SysDictData sysDictData = new SysDictData();
        sysDictData.setDictLabel(dto.getWindowName());
        sysDictData.setDictValue(String.valueOf(icWindow.getId()));
        sysDictData.setDictType(WINDOW_DICT_CODE);
        sysDictData.setListClass("default");
        int row = this.dictDataMapper.insertDictData(sysDictData);

        if (row > 0)
        {
            List<SysDictData> dictDatas = dictDataMapper.selectDictDataByType(WINDOW_DICT_CODE);
            DictUtils.setDictCache(WINDOW_DICT_CODE, dictDatas);
        }
        return insert;
    }

    @Override
    public IcWindowDetailVO detail(Long id) {
        log.info("IIcWindowService_update_id_{}", id);
        IcWindowDetailVO vo = new IcWindowDetailVO();
        IcWindow icWindow = this.icWindowMapper.selectById(id);
        if (null == icWindow) {
            return vo;
        }
        BeanUtils.copyProperties(icWindow, vo);
        vo.setMediatorCommitteeName(this.mediatorCommitteeService.getMediatorCommitteeName(icWindow.getMediatorCommitteeId()));
        log.info("IIcWindowService_update_vo_{}", JSONUtil.toJsonStr(vo));
        return vo;
    }

    @Override
    public List<WindowUserVO> getWindowUserList(Long windowId) {

        return this.icUserWindowMapper.getWindowUserList(windowId);
    }

    @Override
    public boolean checkWindowUserUnique(AddWindowUserDTO dto) {
        return this.icUserWindowMapper.selectCount(Wrappers.<IcUserWindow>lambdaQuery()
                .in(IcUserWindow::getUserId, dto.getUserIdList())
                .eq(IcUserWindow::getWindowId, dto.getWindowId())) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addWindowUser(AddWindowUserDTO dto) {
        log.info("IIcWindowService_addWindowUser_dto_{}", JSONUtil.toJsonStr(dto));
        dto.getUserIdList().forEach(i -> {
            IcUserWindow icUserWindow = new IcUserWindow();
            icUserWindow.setWindowId(dto.getWindowId());
            icUserWindow.setUserId(i);
            icUserWindow.setCreateBy(SecurityUtils.getLoginUser().getUsername());
            icUserWindow.setCreateTime(DateTime.now());
            this.icUserWindowMapper.insert(icUserWindow);
        });
    }

    @Override
    public void removeWindowUser(RemoveWindowUserDTO dto) {
        log.info("IIcWindowService_removeWindowUser_dto_{}", JSONUtil.toJsonStr(dto));
        this.icUserWindowMapper.delete(Wrappers.<IcUserWindow>lambdaQuery()
                .eq(IcUserWindow::getUserId, dto.getUserId())
                .eq(IcUserWindow::getWindowId, dto.getWindowId()));
    }
}
